<?php
namespace app\common\service;

use app\common\service\WeixinService;
use think\Db;
use think\Model;
use think\Request;

use app\common\model\NoticeSend;
use app\common\model\WxMsgLog;
use app\common\helper\WeixinHelper;
use app\common\service\UserService;

class NoticeSendService extends BaseService
{

    public function SendNoticeTest($sid,$noticeId)
    {
        $data['first'] = '这个是一条系统升级通知';
        $data['keyword1'] = '测试账号';
        $data['keyword2'] = '测试主题名称';
        $data['keyword3'] = date("Y-m-d H:i:s");
        $data['keyword4'] = '公众号个人中心';
        $data['remark'] = '收到这个信息惊不惊喜';

        $uid = 0;
        $tpl_id = $noticeId;
        $template_id = '1Py5wItyc769uvygnblg-9DgYAoeErACRbTh1btaMYs';
        $touser = 'oWFBOw16QHLj_yzc4OPMnC2eG7vE';
        $url = 'http://www.baidu.com/?id='.$noticeId;

        $data_in['uid'] = $uid;
        $data_in['tpl_id'] = $tpl_id;
        $data_in['template_id'] = $template_id;
        $data_in['url'] = $url;
        $data_in['data'] = $data;
        $data_in['result_msg'] = '';
        $data_in['touser'] = $touser;

        $this->SendNotice($sid,$noticeId,1,'全部用户',$data_in);



    }

    /**
     * 添加发送任务
     * @param $sid
     * @param $noticeId
     * @param $notice_send_range 1.全部，2.正式学员，3.意向学员，4.潜在学员，5.顾问
     */
    public function AddSendNotice($sid,$noticeId,$notice_send_range)
    {
        $notice_send_range_text = $this->getNoticeSendRangeText($sid,$notice_send_range);
        $user_list = '';
        if(1 == $notice_send_range) {
            $user_list = $this->getUsersListAll($sid);
        }
        if(2 == $notice_send_range) {
            $user_list = $this->getStudentList($sid);
        }
        if(3 == $notice_send_range) {
            $user_list = $this->getCustomerList($sid);
        }
        if(4 == $notice_send_range) {
            $user_list = $this->getFansList($sid);
        }
        if(5 == $notice_send_range) {
            $user_list = $this->getCounselorList($sid);
        }
        if(!$user_list)
        {
            $user_list = $this->getUsersListAll($sid);
        }



        $notice = db('notice')->where(['notice_id'=>$noticeId])->find();
        $title = $notice['notice_title'];
        $remark = $notice['share_description'];


        // notice_id
        // addtime
        // notice_send_range
        // notice_send_range_txt
        // notice_status
        // sid
        $noticeSend = new NoticeSend();
        $noticeSend->sid = $sid;
        $noticeSend->notice_id = $noticeId;
        $noticeSend->notice_send_range = $notice_send_range;
        $noticeSend->notice_send_range_txt = $notice_send_range_text;

        $noticeSend->addtime = time();
        // 状态写成0 表示正在发送，发送完成写成1
        $noticeSend->notice_status = 0;
        $noticeSend->save();

        $notice_send_id = $noticeSend->notice_send_id;

        foreach($user_list as $v) {
            $user_name = $v['user_nickname'];
            $open_id = $v['user_openid'];
            $uid = $v['user_id'];

            $data_in = $this->getNoticeInfo($sid,$uid,$title,$remark,$noticeId,$notice_send_id,$user_name,$open_id,$notice_send_range_text);

            if($data_in !== false){
                $this->SendNotice($sid,$data_in);
            }
        }
        return ['status' => 1, 'msg' => '添加成功'];
    }


    public function getNoticeInfo($sid,$uid,$title,$remark,$noticeId,$notice_send_id,$user_name,$open_id,$text)
    {
        $data['first'] = '这个是一条系统通知'; //('.$text.')
        $data['keyword1'] = $user_name;
        $data['keyword2'] = $title;
        $data['keyword3'] = date("Y-m-d H:i:s");
        $data['keyword4'] = '公众号个人中心';
        $data['remark'] = $remark?$remark:'这个是一条系统通知';

        //$uid = 0;
        $tpl_id = $notice_send_id;
//        $template_id = '1Py5wItyc769uvygnblg-9DgYAoeErACRbTh1btaMYs';
        //获取公告通知模版Id
        $template_id = db('wx_template')->where(['sid' => $sid, 'template_type' => 328])->value('template_no');
        if(!$template_id){
            return false;
        }
        $touser = $open_id; //'oWFBOw16QHLj_yzc4OPMnC2eG7vE';
        //$url = 'https://www.baidu.com/?id='.$noticeId;
        $weixinHelper = new WeixinHelper();

        $url = $weixinHelper->getAppUrl($sid,'/m/html/notice.html?sid='.$sid.'&uid='.$uid.'&id='.$noticeId);

        $data_in['uid'] = $uid;
        $data_in['tpl_id'] = $tpl_id;
        $data_in['template_id'] = $template_id;
        $data_in['url'] = $url;
        $data_in['data'] = $data;
        $data_in['result_msg'] = '';
        $data_in['touser'] = $touser;

        return $data_in;
    }

    /**
     * 获得全部会员
     * @param $sid
     * @return false|\PDOStatement|string|\think\Collection
     */
    public  function getUsersListAll($sid)
    {
        $userService = new UserService();
        $where = ['ui.sid'=>$sid];
        $field = 'user_id,user_nickname,user_openid,ui.addtime';
        $p=1;
        $pageSize = 10000;

        $user_list = $userService->getMemberBaseList($sid,$where,$field,$p,$pageSize);

        return $user_list;
    }

    /**
     * 获得正式学员
     * @param $sid
     */
    public  function getStudentList($sid)
    {
        return $this->getStudentsListByFormalStatus($sid, 1);
    }

    /**
     * 意向客户
     * @param $sid
     */
    public  function getCustomerList($sid)
    {
        return $this->getStudentsListByFormalStatus($sid, 0);
    }

    public function getStudentsListByFormalStatus($sid, $formal_status){
        $where = [
            'ui.sid' => $sid,
            'ui.students_id' => ['>',0],
            'ui.counselor_status' => 0,
            's.formal_status' => $formal_status
        ];
        $field = 'u.user_id,u.user_nickname,u.user_openid';
        $list = db('user_integral ui')
            ->field($field)
            ->join('students s', 'ui.userid = s.uid')
            ->join('user u', 'ui.userid = u.user_id')
            ->where($where)
            ->select();
        return $list;
    }

    /**
     * 获得顾问
     * @param $sid
     * @return false|\PDOStatement|string|\think\Collection
     */
    public  function getCounselorList($sid)
    {
        $userService = new UserService();
        $user_list = $userService->getCounselorList($sid,'',1,10000);
        $user_list = $user_list['content'];
        foreach($user_list as &$v)
        {
            $v['user_id'] = $v['uid'];
        }
        return $user_list;
    }

    /**
     * 获得粉丝
     * @param $sid
     */
    public  function getFansList($sid)
    {
//        $users = WeixinHelper::getUserList($sid);
//        $users = json_decode($users, 1);
//        $open_ids = $users['data']['openid'];
//        return db('user')->where(['user_openid', ['in', $open_ids]])->field('user_id,user_nickname,user_openid')->select();
        $where = [
            'ui.sid' => $sid,
            'ui.counselor_status' => 0,
            'ui.students_id' => 0,
        ];
        $field = 'user_id,user_nickname,user_openid';
        $users = db('user_integral ui')
                ->field($field)
                ->join('user u', 'u.user_id = ui.userid')
                ->where($where)
                ->select();
        return $users;
    }

    public  function getNoticeSendRangeText($sid,$notice_send_range)
    {
        $res = '';
        switch($notice_send_range)
        {
            case 1:
                $res = '全部';
                break;
            case 2:
                $res = '正式学员';
                break;
            case 3:
                $res = '意向客户';
                break;
            case 4:
                $res = '粉丝';
                break;
            case 5:
                $res = '顾问';
                break;
            default:
                $res = '未知';

        }
        return $res;
    }
    /**
     * 写入发送表，不真正发送，等待后台任务发送
     * @param $sid
     * @param $data_in 发送的数组包含 uid,tpl_id,template_id,url,data,result_msg,touser(可以是数组)
     */
    public function SendNotice($sid,$data_in)
    {
        // 写入发送任务表
        $weixinHelper = new WeixinHelper();
        $weixinHelper->addLog($sid,$data_in,0);

    }

    /**
     * 取消发送，已经发送的无法撤销
     * @param $sid 店铺ID
     * @param $noticeSendId 发送任务ID
     * @return bool 是否修改成功
     */
    public function EditNotice($sid,$noticeSendId)
    {
        $return = false;
        // 启动事务
        Db::startTrans();
        try{
            Db::table('notice_send')->where(['notice_send_id'=>$noticeSendId])->update(['notice_status'=>-1]);
            // 只取消未执行的发送任务
            Db::table('wx_msg_log')->where(['tpl_id'=>$noticeSendId,'send_status'=>0])->update(['send_status'=>-1,'result_msg'=>'取消发送']);
            // 提交事务
            Db::commit();
            $return = true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        if($return)
        {
            return ['status' => 1, 'msg' => '取消成功'];
        }
        else
        {
            return ['status' => 0, 'msg' => '取消失败'];
        }
    }

    /**
     * 获得发送任务列表
     * @param $sid
     * @param $notice_id
     */
    public function ListNotice($sid,$notice_id=0,$p = 1, $pageSize = 10)
    {
        $where['sid'] = $sid;
        if($notice_id) {
            $where['notice_id'] = $notice_id;
        }
        $list_count = db('notice_send')->where($where)->count();


        $list = db('notice_send')
            ->where($where)
            ->order('notice_send_id DESC')
            ->limit(($p-1)*$pageSize,$pageSize)
            ->select();

        foreach($list as &$v)
        {
            $notice = db('notice')->where(['notice_id'=>$v['notice_id']])->find();
            $v['notice_title'] = $notice['notice_title'];


            $all = db('wx_msg_log')->where(['tpl_id'=>$v['notice_send_id']])->count();



            $send = db('wx_msg_log')->where(['tpl_id'=>$v['notice_send_id'],'send_status'=>'1'])->count();
            $success = db('wx_msg_log')->where(['tpl_id'=>$v['notice_send_id'],'send_status'=>'1','result_status'=>'1'])->count();

            $fail = $send - $success;
            $wait = $all - $send;

            $v['addtime'] = date("Y-m-d H:i:s",$v['addtime']);

            $v['all'] = $all;
            $v['send'] = $send;
            $v['wait'] = $wait;
            $v['success'] = $success;
            $v['fail'] = $fail;

            //$v['fail_test'] = 'OK';
        }

        return ['content' => $list,'page' =>['count' =>$list_count]];
    }

    /**
     * 获得发送任务列表
     * @param $sid
     * @param $notice_id
     */
    public function ListNoticeSendLog($sid,$notice_id=0,$p = 1, $pageSize = 10)
    {
        $where['sid'] = $sid;
        if($notice_id) {
            $where['tpl_id'] = $notice_id;
        }
        $list_count = db('wx_msg_log')->where($where)->count();


        $list = db('wx_msg_log')
            ->alias('log')
            ->join('user u', 'log.uid = u.user_id','left')
            ->where(['sid'=>$sid])
            ->field('log_id,uid,tpl_id as notice_id,add_time,send_status,send_time,result_status,result_msg,u.user_name,u.user_nickname,u.user_headimgurl')
            ->order('log_id DESC')
            ->limit(($p-1)*$pageSize,$pageSize)
            ->select();

        foreach($list as &$v)
        {
            $v['add_time'] = date("Y-m-d H:i:s",$v['add_time']);
            $v['send_time'] = date("Y-m-d H:i:s",$v['send_time']);
        }



        return ['content' => $list,'page' =>['count' =>$list_count]];
    }

    public function send_tpl()
    {
        $send_list = db('wx_msg_log')->where(['send_status'=>0])->select();

        foreach($send_list as $v)
        {
            $log_id = $v['log_id'];

            // 先修改状态，再发送
            $this->SetSendStatus($log_id,1,'正在发送');
            $data['touser'] = $v['touser'];
            $data['template_id'] = $v['template_id'];
            $data['url'] = $v['url'];

            $data_temp = $v['data'];
            $data_temp2 = '';
            try{
                $data_temp2 = json_decode($data_temp,true);
                if(!is_array($data_temp2))
                {
                    $this->SetSendResultStatus($log_id,-1,'错误：消息内容解码失败，内容是:'.$data_temp);
                }
            }catch(\Exception $e){
                $this->SetSendResultStatus($log_id,-1,'异常：消息内容解码失败，内容是:'.$data_temp);
            }
            $data['data'] = $data_temp2;

            $weixinHelper = new WeixinHelper();
            $res = $weixinHelper->sendTemplateMsgNoLog($v['sid'],$data);
            if($res['status'])
            {
                $this->SetSendStatusOK($log_id,$res['data']);
            }
            else
            {

                $this->SetSendResultStatus($log_id,-1,'失败:'.$res['msg']);
            }
        }

    }
    public function SetSendResultStatus($log_id,$result_status,$result_msg)
    {
        db('wx_msg_log')->where(['log_id'=>$log_id])->update(['result_status'=>$result_status,'result_msg'=>$result_msg]);
    }
    public function SetSendStatus($log_id,$send_status,$result_msg)
    {
        db('wx_msg_log')->where(['log_id'=>$log_id])->update(['send_status'=>$send_status,'result_msg'=>$result_msg]);
    }
    public function SetSendStatusOK($log_id,$messageId)
    {
        //'messageId,'=>$messageId,
        db('wx_msg_log')->where(['log_id'=>$log_id])->update(['send_status'=>1,'result_status'=>1,'result_msg'=>'发送成功']);
    }


    public function forwardNotice($sid, $notice_id, $notice_send_range){
        $sys_notice = db('notice')->where(['notice_id' => $notice_id, 'notice_status' => 1, 'sid' => 0])->find();
        if(!$sys_notice){
            return ['status' => 0, 'msg' => '公告不存在'];
        }
        $data = [
            'notice_title' => $sys_notice['notice_title'],
            'notice_content' => $sys_notice['notice_content'],
            'notice_author' => $sys_notice['notice_author'],
            'notice_keyword' => $sys_notice['notice_keyword'],
            'notice_sort' => $sys_notice['notice_sort'],
            'notice_status' => $sys_notice['notice_status'],
            'edit_time' => time(),
            'istop' => $sys_notice['istop'],
            'send_obj' => 2,
            'notice_type' => $sys_notice['notice_type'],
            'share_title' => $sys_notice['share_title'],
            'share_img' => $sys_notice['share_img'],
            'share_description' => $sys_notice['share_description'],
            'sid' => $sid,
        ];

        $r = $insert_id = db('notice')->insertGetId($data);
        if(!$r){
            return ['status' => 0, 'msg' => '操作失败'];
        }

        return $this->AddSendNotice($sid, $insert_id, $notice_send_range);
    }
}